package com.yangaobo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yangaobo.dto.RoleInsertDTO;
import com.yangaobo.dto.RolePageDTO;
import com.yangaobo.dto.RoleUpdateDTO;
import com.yangaobo.entity.Role;
import com.yangaobo.excel.RoleExcel;
import com.yangaobo.exception.ServerErrorException;
import com.yangaobo.mapper.RoleMapper;
import com.yangaobo.service.RoleService;
import com.yangaobo.vo.RoleVO;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 杨奥博
 */
@Service
@CacheConfig(cacheNames = "role")
public class RoleServiceImpl implements RoleService {
    @Resource
    private RoleMapper roleMapper;

    @CacheEvict(allEntries = true)
    @Override
    public int insert(RoleInsertDTO dto) {
        // 将DTO转换为Entity（使用Hutool工具类BeanUtil复制属性）
        Role role = BeanUtil.copyProperties(dto, Role.class);

        if(StrUtil.isBlank(dto.getInfo())) {
            role.setInfo("暂无描述");
        }
        role.setVersion(0L);
        role.setDeleted(0);
        role.setCreated(LocalDateTime.now());
        role.setUpdated(LocalDateTime.now());
        int result = roleMapper.insert(role);
        if (result <= 0) {
            throw new ServerErrorException("DB添加失败");
        }
        return result;
    }

    @Cacheable(key = "#root.methodName + ':' + #p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public Role select(Long id) {
        Role result = roleMapper.select(id);
        if(ObjectUtil.isNull(result)) {
            throw new ServerErrorException("DB查询失败");
        }
        return result;
    }

    @Cacheable(key = "#root.methodName", unless = "#result == null")
    @Override
    public List<RoleVO> list() {
        return roleMapper.list(new RolePageDTO())
                .stream()
                .map(role -> BeanUtil.copyProperties(role, RoleVO.class))
                .collect(Collectors.toList());
    }

    @Cacheable(key = "#root.methodName + ':' + #p0.toString()",
            condition = "#p0 != null",
            unless = "#result == null")
    @Override
    public PageInfo<Role> page(RolePageDTO dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        return new PageInfo<>(roleMapper.list(dto));
    }

    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int update(RoleUpdateDTO dto) {
        Role role = roleMapper.select(dto.getId());
        if(ObjectUtil.isNull(role)){
            throw new ServerErrorException("DB查询失败");
        }
        // 将DTO中的值复制到Entity中
        BeanUtil.copyProperties(dto, role);
        // 设置默认值
        role.setUpdated(LocalDateTime.now());
        // DB修改
        int result = roleMapper.update(role);
        if (result <= 0) {
            throw new ServerErrorException("DB修改失败");
        }
        return result;
    }

    @CacheEvict(allEntries = true)
    @Override
    public int delete(Long id) {
        int result = roleMapper.delete(id);
        if (result <= 0) {
            throw new ServerErrorException("DB删除失败");
        }
        return result;
    }

    @CacheEvict(allEntries = true)
    @Override
    public int deleteBatch(List<Long> ids) {
        int result = roleMapper.deleteBatch(ids);
        if (result <= 0) {
            throw new ServerErrorException("DB删除失败");
        }
        return result;
    }


    public List<RoleExcel> getExcelData() {
        return roleMapper.list(new RolePageDTO())
                .stream()
                .map(role -> BeanUtil.copyProperties(role, RoleExcel.class))
                .collect(Collectors.toList());
    }
    @Cacheable(key = "#root.methodName + ':' + #p0",
            condition = "#p0 != null",
            unless = "#result == null")
    @Override
    public List<Role> listByEmpId(Long empId) {
        return roleMapper.listByEmpId(empId);
    }

    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateByEmpId(Long empId, List<Long> ids) {
        List<Role> roles = roleMapper.listByEmpId(empId);
        if (!roles.isEmpty()) {
            int result = roleMapper.deleteByEmpId(empId);
            if (result <= 0) {
                throw new ServerErrorException("DB删除失败");
            }
        }

        if(CollectionUtil.isEmpty(ids)) {
            return 1;
        }
        int result = roleMapper.updateByEmpId(empId, ids);
        if (result <= 0) {
            throw new ServerErrorException("DB修改失败");
        }
        return result;
    }

}
